package com.climber.android.commonres.ui.dialog;

import android.content.Intent;
import android.content.pm.PackageInfo;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.view.Gravity;
import android.view.View;
import android.widget.ImageView;

import androidx.annotation.NonNull;
import androidx.fragment.app.BaseDialogFragment;
import androidx.fragment.app.FragmentActivity;

import com.bumptech.glide.Glide;
import com.climber.android.commonres.R;
import com.climber.android.commonres.entity.NavigationMapObject;
import com.climber.android.commonsdk.helper.BundleHelper;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import io.ganguo.library.mvp.util.ActivityUtils;
import io.ganguo.library.mvp.util.AppUtils;
import io.ganguo.library.mvp.util.StringUtils;
import io.ganguo.library.mvp.util.ToastHelper;
import io.library.android.adapter.LQRAdapterForRecyclerView;
import io.library.android.adapter.LQRViewHolderForRecyclerView;
import io.library.android.recyclerview.LQRRecyclerView;

/**
 * Created by Mikes at 2019/4/28 4:56 PM
 */
public class ChooseMapAppDialog extends BaseDialogFragment {
    public static final String PACKAGE_BAIDU_MAP = "com.baidu.BaiduMap";
    public static final String PACKAGE_GAODE_MAP = "com.autonavi.minimap";
    public static final String PACKAGE_TENCENT_MAP = "com.tencent.map";
    public static final String PACKAGE_GOOGLE_MAP = "com.google.android.apps.maps";

    public static void showNavigateMapDialog(FragmentActivity fragmentActivity,
                                             double lon,
                                             double lat,
                                             String address) {
        if (lon == 0 && lat == 0) {
            return;
        }

        //筛选手机内是否安装了百度，高度，腾讯，谷歌地图，将所安装的地图应用展示，用户选择某个地图应用时，将坐标系传入。
        boolean installBaiDuMap = AppUtils.isAvailable(ChooseMapAppDialog.PACKAGE_BAIDU_MAP);
        boolean installGaoDeMap = AppUtils.isAvailable(ChooseMapAppDialog.PACKAGE_GAODE_MAP);
        boolean installTencentMap = AppUtils.isAvailable(ChooseMapAppDialog.PACKAGE_TENCENT_MAP);
        boolean installGoogleMap = AppUtils.isAvailable(ChooseMapAppDialog.PACKAGE_GOOGLE_MAP);

        if (installBaiDuMap || installGaoDeMap || installTencentMap || installGoogleMap) {
            ChooseMapAppDialog chooseMapAppDialog = new ChooseMapAppDialog();

            chooseMapAppDialog.setArguments(new BundleHelper()
                    .putSerializable("navigationObject", new NavigationMapObject(lon, lat, address))
                    .build());
            chooseMapAppDialog.show(fragmentActivity.getSupportFragmentManager(), "dialog_choose_map");
        } else {
            ToastHelper.toastMessage("您尚未安装地图APP。不能使用导航。");
        }
    }

    LQRRecyclerView lqrMapApps;

    @Override
    public void onStart() {
        super.onStart();
        setLocation(Gravity.BOTTOM);
    }

    @Override
    protected int getLayoutResId() {
        return R.layout.com_web_dialog_choose_map_app;
    }

    @Override
    protected void initView(@NonNull View dialogView) {
        getDialog().setCanceledOnTouchOutside(true);

        lqrMapApps = dialogView.findViewById(R.id.lqrMapApps);
    }

    @Override
    protected void initData() {
        if (getArguments() == null || getArguments().getSerializable("navigationObject") == null) {
            dismiss();
            return;
        }

        final NavigationMapObject navigationObject = (NavigationMapObject) getArguments().getSerializable("navigationObject");

        if (navigationObject == null) {
            dismiss();
            return;
        }

        PackageInfo baiDuInfo = AppUtils.getSpecialPackageInfo(ChooseMapAppDialog.PACKAGE_BAIDU_MAP);
        PackageInfo gaoDeInfo = AppUtils.getSpecialPackageInfo(ChooseMapAppDialog.PACKAGE_GAODE_MAP);
        PackageInfo tencentInfo = AppUtils.getSpecialPackageInfo(ChooseMapAppDialog.PACKAGE_TENCENT_MAP);
        PackageInfo googleIno = AppUtils.getSpecialPackageInfo(ChooseMapAppDialog.PACKAGE_GOOGLE_MAP);

        List<PackageInfo> mapApps = new ArrayList<>();
        if (baiDuInfo != null) {
            mapApps.add(baiDuInfo);
        }
        if (gaoDeInfo != null) {
            mapApps.add(gaoDeInfo);
        }
        if (tencentInfo != null) {
            mapApps.add(tencentInfo);
        }
        if(googleIno != null){
            mapApps.add(googleIno);
        }

        LQRAdapterForRecyclerView<PackageInfo> adapter = new LQRAdapterForRecyclerView<PackageInfo>(getContext(), mapApps, R.layout.com_web_rv_item_choose_map_app) {
            @Override
            public void convert(LQRViewHolderForRecyclerView helper, PackageInfo item, int position) {
                Drawable appIcon = item.applicationInfo.loadIcon(AppUtils.getApp().getPackageManager());
                Glide.with(AppUtils.getApp())
                        .load(appIcon)
                        .into((ImageView) helper.getView(R.id.ivAppIcon));

                helper.setText(R.id.tvAppName, StringUtils.getNonNullString(item.applicationInfo.loadLabel(AppUtils.getApp().getPackageManager())));
            }
        };
        lqrMapApps.setAdapter(adapter);

        adapter.setOnItemClickListener((helper, parent, itemView, position) -> {
            dismiss();
            
            switch (adapter.getData().get(position).packageName) {
                case ChooseMapAppDialog.PACKAGE_BAIDU_MAP:
                    openBaiDuNav(navigationObject);
                    break;
                case ChooseMapAppDialog.PACKAGE_GAODE_MAP:
                    openGaoDeNav(navigationObject);
                    break;
                case ChooseMapAppDialog.PACKAGE_TENCENT_MAP:
                    openTencentNav(navigationObject);
                    break;
                case ChooseMapAppDialog.PACKAGE_GOOGLE_MAP:
                    openGoogleNav(navigationObject);
                    break;
            }
        });
    }

    /**
     * BD-09 坐标转换成 GCJ-02 坐标
     *
     * 百度坐标系
     */
    public static NavigationMapObject BD2GCJ(NavigationMapObject bd) {
        try{
            double x = bd.getLon() - 0.0065, y = bd.getLat() - 0.006;
            double z = Math.sqrt(x * x + y * y) - 0.00002 * Math.sin(y * Math.PI);
            double theta = Math.atan2(y, x) - 0.000003 * Math.cos(x * Math.PI);

            double tempLon = z * Math.cos(theta);
            double tempLat = z * Math.sin(theta);

            BigDecimal desLat = new BigDecimal(tempLat);
            BigDecimal desLon = new BigDecimal(tempLon);

            return new NavigationMapObject(desLon.setScale(6, BigDecimal.ROUND_HALF_DOWN).doubleValue(),
                    desLat.setScale(6, BigDecimal.ROUND_HALF_DOWN).doubleValue(),
                    bd.getAddress());
        } catch (Exception e){
            return bd;
        }
    }

    /**
     * GCJ-02 坐标转换成 BD-09 坐标
     *
     * 腾讯地图和高德地图都采用了GCJ-02火星坐标系
     */
    public static NavigationMapObject GCJ2BD(NavigationMapObject bd) {
        try{
            double x = bd.getLon(), y = bd.getLat();
            double z = Math.sqrt(x * x + y * y) + 0.00002 * Math.sin(y * Math.PI);
            double theta = Math.atan2(y, x) + 0.000003 * Math.cos(x * Math.PI);

            double tempLon = z * Math.cos(theta) + 0.0065;
            double tempLat = z * Math.sin(theta) + 0.006;

            BigDecimal desLat = new BigDecimal(tempLat);
            BigDecimal desLon = new BigDecimal(tempLon);

            return new NavigationMapObject(desLon.setScale(6, BigDecimal.ROUND_HALF_DOWN).doubleValue(),
                    desLat.setScale(6, BigDecimal.ROUND_HALF_DOWN).doubleValue(),
                    bd.getAddress());
        } catch (Exception e){
            return bd;
        }
    }

    //打开百度地图导航
    private void openBaiDuNav(NavigationMapObject navigationObject) {
        NavigationMapObject endPoint = GCJ2BD(navigationObject); //坐标转换
        Intent baiduMapIntent = new Intent();
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append("baidumap://map/direction?")
                .append("destination=latlng:").append(endPoint.getLat()).append(",").append(endPoint.getLon())
                .append("|name:").append(endPoint.getAddress())
                .append("&mode=").append("driving")
                .append("&src=").append(AppUtils.getAppPackageName());
        baiduMapIntent.setData(Uri.parse(stringBuffer.toString()));
        if(baiduMapIntent.resolveActivity(AppUtils.getApp().getPackageManager()) != null){
            ActivityUtils.startActivity(baiduMapIntent);
        }
    }

    //打开高德地图导航
    private void openGaoDeNav(NavigationMapObject navigationObject) {
        NavigationMapObject endPoint = navigationObject; //坐标转换
        StringBuffer stringBuffer = new StringBuffer();
        //路径规划
        stringBuffer.append("amapuri://route/plan/?")
                .append("sourceApplication=").append(AppUtils.getAppName())
                .append("&dlat=").append(endPoint.getLat())
                .append("&dlon=").append(endPoint.getLon())
                .append("&dname=" + navigationObject.getAddress())
                .append("&dev=").append(0)
                .append("&t=").append(0); //0 驾车

        Intent gaodeMapIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(stringBuffer.toString()))
                    .setPackage(PACKAGE_GAODE_MAP);
        if(gaodeMapIntent.resolveActivity(AppUtils.getApp().getPackageManager()) != null){
            ActivityUtils.startActivity(gaodeMapIntent);
        }
    }

    //打开腾讯地图导航
    private void openTencentNav(NavigationMapObject navigationObject) {
        NavigationMapObject endPoint = navigationObject; //坐标转换
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append("qqmap://map/routeplan?")
                .append("type=").append("drive")
                .append("&fromcoord=").append("CurrentLocation")
                .append("&to=").append(navigationObject.getAddress())
                .append("&tocoord=").append(endPoint.getLat()).append(",").append(endPoint.getLon()); //tocoord	终点坐标 (纬度，经度)

        Intent tencentMapIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(stringBuffer.toString()));
        if(tencentMapIntent.resolveActivity(AppUtils.getApp().getPackageManager()) != null){
            ActivityUtils.startActivity(tencentMapIntent);
        }
    }

    //打开谷歌地图
    private void openGoogleNav(NavigationMapObject navigationObject){
        NavigationMapObject endPoint = navigationObject; //坐标转换
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append("https://www.google.com/maps/dir/?api=1")
                .append("&destination=").append(endPoint.getLat()).append(",").append(endPoint.getLon())
                .append("&q=").append(endPoint.getAddress())
                .append("&travelmode=").append("driving");

        Intent googleMapIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(stringBuffer.toString()))
                .setPackage(PACKAGE_GOOGLE_MAP);
        googleMapIntent.setClassName(PACKAGE_GOOGLE_MAP, "com.google.android.maps.MapsActivity");

        if(googleMapIntent.resolveActivity(AppUtils.getApp().getPackageManager()) != null){
            ActivityUtils.startActivity(googleMapIntent);
        }
    }
}
